package org.brownflat.dbinit.oracle;

import org.apache.log4j.Logger;
import org.brownflat.dbinit.PatchSequenceManager;
import org.brownflat.dbinit.upgrade.Upgrade;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * <p>Database Init &copy Rupert Jones 2013</p>
 *
 * @author rup
 */
public class OraclePatchSequenceManager implements PatchSequenceManager {

    private DataSource dataSource;
    private static final Logger LOG = Logger.getLogger(OraclePatchSequenceManager.class);
    private String patchTable = "DB_INIT_PATCHES";


    public OraclePatchSequenceManager(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Override
    public int getCurrentSequence() {
        String sql = "SELECT LAST_PATCH FROM " + patchTable;
        Connection connection = null;
        Statement statement = null;
        int value = -1;
        try {
            connection = dataSource.getConnection();
            statement = connection.createStatement();
            ResultSet rs = statement.executeQuery(sql);
            if(rs.next()) {
                value = rs.getInt("LAST_PATCH");
            }
        } catch (SQLException e) {
            LOG.error(e);
            LOG.info("Error finding patch table, assuming not initialised.");
        } finally {
            try {
                statement.close();
                connection.close();
            } catch (SQLException sqle) {
                throw new RuntimeException(sqle);
            } finally {
                return value;
            }
        }
    }

    @Override
    public void markAsApplied(Upgrade upgrade) {
        Connection connection = null;
        Statement statement = null;
        try {
            connection = dataSource.getConnection();
            statement = connection.createStatement();
            statement.executeUpdate("UPDATE " + patchTable + " SET LAST_PATCH=" + upgrade.getSequence());
        } catch (Exception e) {
            LOG.error(e);
        } finally {
            try {
                statement.close();
                connection.close();
            } catch (SQLException sqle) {
                throw new RuntimeException(sqle);
            }
        }
    }

    public void setPatchTable(String patchTable) {
        this.patchTable = patchTable;
    }
}
